# -*- coding:utf-8 -*-
import tushare as ts
from ultils import sendMail, Hotmail
import procDB
from datetime import datetime, timedelta
from logger import loggger
from dingtalkchatbot.chatbot import DingtalkChatbot

dbfile = 'Alerm.db'
csvname = '%s.csv' % datetime.now().strftime('%Y%m%d')  #调用tushare后要输出的csv文件名，文件中包含了当前获取股票信息
TIMEOUT = -10    # 自最后一次报警时间后，允许再次报警的时长

def getAlermList():
    tdelta = datetime.now() + timedelta(hours=TIMEOUT)
    print(tdelta)
    sql = 'select [Id], [Type], [Code], [Price], [Enabled] from stock where ([Alermed] = 0 or ([LastAlermTime] < ?))   and [Enabled] = ?'
    rows = procDB.fetchall(dbfile, sql, (tdelta, 1))
    return rows

def comparePrice(rows):
    for row in rows:
        df = ts.get_realtime_quotes(row['Code'])
        if row['Type'] == 1 and row['Price'] <= float(df['price']):
            #alerm2Mail(row, df)
            alerm2DingDing(row, df)
        if row['Type'] == 2 and row['Price'] >= float(df['price']):
            #alerm2Mail(row, df)
            alerm2DingDing(row, df)

def alerm2Mail(row, df):
    df.to_csv(csvname, columns=['code', 'name', 'price', 'bid', 'ask', 'volume', 'amount', 'time'])
    subject = '你监测的 %s( %s ) 已达到你期待的最 %s 临界值，请你及时处理' % (df['name'].values[0], df['code'].values[0], row['Type']==1 and '高' or '低')
    #sendMail('mgjdrobot@21cn.com', '13639098303@139.com', subject, [csvname])
    hotmail = Hotmail('mgjdrobot', 'Lyp82nlf')
    hotmail.send('13639098303@139.com', '重要提示', subject)
    loggger.info('已发送邮件提醒，内容为：%s' % subject)
    updateAlermTime(row)



def alerm2DingDing(row, df):
    subject = '你监测的 %s( %s ) 已达到你期待的最 %s 临界值，请你及时处理' % (df['name'].values[0], df['code'].values[0], row['Type'] == 1 and '高' or '低')
    webhook = 'https://oapi.dingtalk.com/robot/send?access_token=bf4b18618e45f865065b38285134adffc535d73fa46dbcebcaf7891594ccea0d'
    xiaoding = DingtalkChatbot(webhook)
    xiaoding.send_text(subject, is_at_all=True)



def updateAlermTime(row):
    sql = 'UPDATE stock SET  [Alermed] = 1, [LastAlermTime]= ? WHERE ID = ? '
    procDB.update(dbfile, sql, [(datetime.now(), row['id'])])

def main():
    loggger.info('开始运行，当前获取数据中.....！')
    rows = getAlermList()
    comparePrice(rows)
    loggger.info('结束运行。')

if __name__ == '__main__':
    main()
